<?php

namespace App\Admin\Forms\Aliyun;

use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Domain\Domain;
use App\Models\Aliyun;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class DomainRemarkForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function handle(array $input): JsonResponse
    {
        $remark = $input['remark'] ?? '';
        $instanceId = $input['instance_id'];

        $aliyun = Aliyun::ofAdmin()->find($this->payload['aliyun']);
        $aliyun->initClient();

        Domain::v20180129()
            ->saveBatchDomainRemark()
            ->withInstanceIds($instanceId)
            ->withRemark($remark)
            ->request();

        return $this->response()->success('操作成功')->refresh();
    }

    public function form(): void
    {
        $this->hidden('instance_id');
        $this->textarea('remark', '备注');
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function default(): array
    {
        $aliyun = Aliyun::ofAdmin()->find($this->payload['aliyun']);
        $aliyun->initClient();

        $res = Domain::v20180129()
            ->queryDomainByDomainName()
            ->withDomainName($this->payload['domain'])
            ->request();

        return [
            'instance_id' => $res->get('InstanceId'),
            'remark' => $res->get('Remark')
        ];
    }
}
